﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Vit.Common
{
    public class Events
    {
        private readonly static ConcurrentDictionary<string, EventExecutor> events = new ConcurrentDictionary<string,EventExecutor>();

        public static void Bind(string eventName, Func<object, string> executor)
        {
            eventName = eventName.ToLower();
            var eve = events.GetOrAdd(eventName, new EventExecutor(eventName));

            eve.EnQueueExecutor(executor);
        }

        public static void Trigger(string eventName, object sender)
        {
            eventName = eventName.ToLower();
            var eve = events.GetOrAdd(eventName, new EventExecutor(eventName));

            eve.Execute(sender);
        }
    }

    internal class EventExecutor
    {
        private string name;
        private ConcurrentQueue<Func<object, string>> executorQueue;

        public EventExecutor(string name)
        {
            this.name = name;
            executorQueue = new ConcurrentQueue<Func<object, string>>();
        }

        public void EnQueueExecutor(Func<object, string> executor)
        {
            executorQueue.Enqueue(executor);
        }

        public string Execute(object sender)
        {
            string msg = string.Empty;
            foreach(var executor in executorQueue)
            {
                msg += executor(sender);
            }
            return msg;
        }
    }
}
